<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" :title="getTitle" width="700px" @ok="handleSubmit" @close="handleClose" destroyOnClose>
    <MyAlert
      type="warning"
      style="margin-bottom: -2px"
      message="新增接收人后，系统将自动 发送验证信息 到所填手机号和邮箱，通过验证后 方可接收消息。"
    />
    <BasicForm @register="registerForm" ref="formRef">
      <template #wxMpOpenId="{ model, field }">
        <a-row :gutter="8">
          <a-col :sm="24" :md="24" :lg="24" :xl="24">
            <a-input v-model:value="model[field]" class="input-verify-code" placeholder="扫码下方二维码自动填充" readonly />
          </a-col>
          <a-col :sm="24" :md="24" :lg="24" :xl="24" style="margin-top: 5px">
            <ImagePreview :image-list="[{ src: model['wxMpQrCodeUrl'], width: 80, height: 80 }]" />
          </a-col>
        </a-row>
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref, useAttrs, onMounted, onUnmounted } from "vue"
  import { BasicForm, useForm } from "/@/components/Form"
  import { ImagePreview } from "/@/components/Preview/index"
  import { BasicDrawer, useDrawerInner } from "/@/components/Drawer"
  import { formSchema } from "../receiver.data"
  import { saveOrUpdateReceiver, getReceiver, getWxMpQrcode } from "../receiver.api"
  import { getWxOpenIdByScan } from "/@/api/index"
  import MyAlert from "/@/components/My/MyAlert.vue"
  import { useMessage } from "/@/hooks/web/useMessage"

  // 声明Emits
  const emit = defineEmits(["success", "register"])
  const { createMessage } = useMessage()
  const attrs = useAttrs()
  const isUpdate = ref(true)
  const formRef = ref()
  let interval: any = null
  const [registerForm, { setProps, resetFields, setFieldsValue, validate }] = useForm({
    schemas: formSchema,
    labelWidth: 90,
    showActionButtonGroup: false,
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 20 },
    },
  })
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    resetFields()
    isUpdate.value = !!data?.isUpdate
    setDrawerProps({ confirmLoading: false, loading: true })
    try {
      if (unref(isUpdate)) {
        const record = await getReceiver({ id: data.record.id })
        setFieldsValue({ ...record })
      } else {
        const wxMpQrCodeUrl = await getWxMpQrcode()
        setFieldsValue({ wxMpQrCodeUrl })
      }
    } finally {
      setDrawerProps({ loading: false })
    }

    if (interval) {
      clearInterval(interval)
      interval = null
    }
    interval = setInterval(async () => {
      try {
        const openId = await getWxOpenIdByScan()
        if (openId) {
          setFieldsValue({ wxMpOpenId: openId })
          clearInterval(interval)
          interval = null
        }
      } catch (e) {
        console.error(e)
      }
    }, 2000)
  })

  const getTitle = computed(() => (!unref(isUpdate) ? "新增接收人" : "编辑接收人"))

  onUnmounted(() => {
    clearInterval(interval)
    interval = null
  })

  const handleClose = () => {
    clearInterval(interval)
    interval = null
  }
  async function handleSubmit() {
    try {
      const values = await validate()
      setDrawerProps({ confirmLoading: true })
      //提交表单
      await saveOrUpdateReceiver(values, isUpdate.value)
      closeDrawer()
      createMessage.success('更新成功')
      emit("success")
    } finally {
      setDrawerProps({ confirmLoading: false })
    }
  }
</script>
